package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * 在RabbitMQ中使用ActiveMQ的主题订阅模式
 */
public class 测试ActiveMQ的订阅消费01 {
    public static final String exchange = "ActiveMQ_Topic";

    public static void main(String[] args) {
        // 通过链接工程创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        try {
            connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            // 队列名字全部留空 等系统生成
            channel.queueDeclare("",true,false,false,null);
            // 只需要绑定交换机和key到 生产者的交换机和key就可以多个消费者同时消费
            channel.exchangeDeclare(exchange, BuiltinExchangeType.TOPIC);
            channel.queueBind("",exchange,"a");
            channel.basicConsume("",true,new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println(new String(body, StandardCharsets.UTF_8));
                }
            });
        } catch (TimeoutException | IOException e) {
            e.printStackTrace();
        }
    }
}
